﻿// Copyright Microsoft

using System;
using System.Windows.Forms;
using System.Net;

namespace Microsoft.Samples.SqlServer.Activities
{
  public partial class LoginForm : Form
  {
    public delegate void ActivityFormEventHandler(object sender, ActivityFormEventArgs e);
    public event ActivityFormEventHandler DataAvailable;
    public ICredentials networkCredential = null;

    private ConnectionContext connectionContext = ConnectionContext.IntegratedSecurity;

    public LoginForm()
    {
      InitializeComponent();
    }

    private void OKButton_Click(object sender, EventArgs e)
    {
      switch (domainComboBox.SelectedIndex)
      {
        case 0:
          networkCredential = CredentialCache.DefaultCredentials;
          break;
        case 1:
          {
            networkCredential = new NetworkCredential(userNameTextBox.Text, passwordTextBox.Text);
            connectionContext = ConnectionContext.SqlAzure;            
            break;
          }
      }
     
      if (this.DataAvailable != null)
        DataAvailable(this, new ActivityFormEventArgs(networkCredential, connectionContext));

      this.Close();
    }

    private void cancelButton_Click(object sender, EventArgs e)
    {
      if (this.DataAvailable != null)
        DataAvailable(this, new ActivityFormEventArgs(networkCredential, connectionContext));
      this.Close();
    }

    private void domainComboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
      groupBox.Enabled = domainComboBox.SelectedIndex == 0 ? false : true;
    }
  }

  public enum ConnectionContext
  {
    IntegratedSecurity, SqlAzure
  }

  public class ActivityFormEventArgs : EventArgs
  {
    public ICredentials NetworkCredential { get; set; }
    public ConnectionContext ConnectionContext { get; set; }

    public ActivityFormEventArgs(ICredentials networkCredential, ConnectionContext connectionContext)
    {
      this.NetworkCredential = networkCredential;
      this.ConnectionContext = connectionContext;
    }
  }
}
